package cn.com.zpark.druid;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @PackageName: cn.com.zpark.druid
 * @ClassName: DruidUtils
 * @Description:Druid数据库连接池
 * @author: RZS
 * @date: 2021/10/30  16:16
 */
public class DruidUtils {
    private static DataSource dataSource;

    // 初始化连接池
    static {
        InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
        // 创建properties配置文件
        Properties p = new Properties();

        try {
            // 加载配置文件
            p.load(inputStream);
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取连接池对象
    public static DataSource getDataSource() {
        return dataSource;
    }

    // 获取连接
    public static Connection getConn() throws SQLException {
        return dataSource.getConnection();
    }

    // 关闭连接
    public static void close(ResultSet res, Statement stat, Connection conn){
        if (res != null) {
            try {
                res.close();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }

        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
